package com.firefly.web.controller.home.test;

import com.firefly.util.handle.FireflyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: 同步锁与异步操作
 * @author: lzg(萤火科技 ： 854378082 @ qq.com)
 * @date: 2023/4/26
 **/
@RestController
@Slf4j
public class SyncController {

    /*
    * redis分布式锁
    * */
    @Autowired
    private RedisLockRegistry redisLockRegistry;
    /*
    * Java 本身提供的ReentrantLock锁机制挺好用~
    * 最多等待2秒，如果拿不到锁就返回空
    * */
    private static ReentrantLock lock = new ReentrantLock();
    @GetMapping("sync/reentrantlock")
    public void testReentrantLock() throws InterruptedException {
        if (!lock.tryLock(2, TimeUnit.SECONDS)){
            throw new FireflyException(403,"没有拿到锁");
        }
        try{
            log.debug("lock ---------- out");
            Thread.sleep(500);
            // lock.lock();
        }catch (Exception e){
            throw new FireflyException(500,"");
        }finally {
            lock.unlock();
        }
    }

    // 加锁以后要等上一个线程运行结束下一个线程的调用才会开始，mysql 事务要放到方法内
    @GetMapping("sync/sync")
    public synchronized void testSync() throws InterruptedException {
        log.debug("sync ---------- out");
        Thread.sleep(1500);
    }

    @GetMapping("sync/redislock")
    public void testRedisLock() throws InterruptedException {
        Lock lock = redisLockRegistry.obtain("sss0001");
        try {
            if (!lock.tryLock(2, TimeUnit.SECONDS)){
                throw new FireflyException(403,"没有拿到锁");
            }
            log.debug("lock ---------- out");
            Thread.sleep(500);
        } finally {
            // 一定要解锁
            lock.unlock();
        }
    }
}
